// API服务 - 与后端通信
class ApiService {
  constructor() {
    // 直接请求后端服务，不使用代理
    this.baseUrl = 'http://localhost:8080'
    this.timeout = 30000 // 30秒超时
  }

  // 通用请求方法
  async request(url, options = {}) {
    const config = {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        // 添加CORS相关请求头
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Requested-With',
        'Access-Control-Allow-Credentials': 'true',
        // 添加自定义请求头标识
        'X-Requested-With': 'XMLHttpRequest',
        'X-Frontend-Source': 'Vue-App',
        ...options.headers
      },
      mode: 'cors', // 明确指定CORS模式
      credentials: 'include', // 包含凭证
      timeout: this.timeout,
      ...options
    }

    try {
      const response = await fetch(`${this.baseUrl}${url}`, config)
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }

      const contentType = response.headers.get('content-type')
      if (contentType && contentType.includes('application/json')) {
        return await response.json()
      } else {
        return await response.text()
      }
    } catch (error) {
      console.error('API请求失败:', error)
      throw error
    }
  }

  // GET请求
  async get(url, params = {}) {
    const queryString = new URLSearchParams(params).toString()
    const fullUrl = queryString ? `${url}?${queryString}` : url
    return this.request(fullUrl)
  }

  // POST请求
  async post(url, data = {}) {
    return this.request(url, {
      method: 'POST',
      body: JSON.stringify(data)
    })
  }

  // PUT请求
  async put(url, data = {}) {
    return this.request(url, {
      method: 'PUT',
      body: JSON.stringify(data)
    })
  }

  // DELETE请求
  async delete(url) {
    return this.request(url, {
      method: 'DELETE'
    })
  }

  // 上传文件
  async upload(url, file, additionalData = {}) {
    const formData = new FormData()
    formData.append('file', file)
    
    Object.keys(additionalData).forEach(key => {
      formData.append(key, additionalData[key])
    })

    return this.request(url, {
      method: 'POST',
      body: formData,
      headers: {} // 让浏览器自动设置Content-Type
    })
  }

  // === 录制相关API ===

  // 启动录制
  async startRecording(options = {}) {
    try {
      const response = await this.post('/recording/start', {
        startUrl: options.startUrl || '',
        name: options.name || `录制会话 ${new Date().toLocaleString()}`,
        settings: options.settings || {}
      })
      
      return {
        success: true,
        sessionId: response.sessionId,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 停止录制
  async stopRecording(sessionId) {
    try {
      const response = await this.post('/recording/stop', { sessionId })
      
      return {
        success: true,
        steps: response.steps || [],
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 获取录制状态
  async getRecordingStatus(sessionId) {
    try {
      const response = await this.get(`/recording/status/${sessionId}`)
      return {
        success: true,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 获取录制结果
  async getRecordingResult(sessionId) {
    try {
      const response = await this.get(`/recording/result/${sessionId}`)
      return {
        success: true,
        steps: response.steps || [],
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // === 脚本执行相关API ===

  // 执行脚本
  async executeScript(steps, options = {}) {
    try {
      const response = await this.post('/execution/run', {
        steps,
        options: {
          speed: options.speed || 1,
          headless: options.headless !== false,
          screenshotOnError: options.screenshotOnError !== false,
          ...options
        }
      })
      
      return {
        success: true,
        executionId: response.executionId,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 执行单个步骤
  async executeStep(step, options = {}) {
    try {
      const response = await this.post('/execution/step', {
        step,
        options
      })
      
      return {
        success: true,
        result: response.result,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 获取执行状态
  async getExecutionStatus(executionId) {
    try {
      const response = await this.get(`/execution/status/${executionId}`)
      return {
        success: true,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 暂停执行
  async pauseExecution(executionId) {
    try {
      const response = await this.post('/execution/pause', { executionId })
      return {
        success: true,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 恢复执行
  async resumeExecution(executionId) {
    try {
      const response = await this.post('/execution/resume', { executionId })
      return {
        success: true,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 停止执行
  async stopExecution(executionId) {
    try {
      const response = await this.post('/execution/stop', { executionId })
      return {
        success: true,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // === 脚本管理相关API ===

  // 保存脚本
  async saveScript(scriptData) {
    try {
      const response = await this.post('/api/scripts/save', scriptData)
      return {
        success: true,
        scriptId: response.scriptId,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 加载脚本
  async loadScript(scriptId) {
    try {
      const response = await this.get(`/api/scripts/${scriptId}`)
      return {
        success: true,
        script: response,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 获取脚本列表
  async getScripts(options = {}) {
    try {
      const response = await this.get('/api/scripts', {
        page: options.page || 1,
        limit: options.limit || 20,
        search: options.search || ''
      })
      return {
        success: true,
        scripts: response.scripts || [],
        total: response.total || 0,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 删除脚本
  async deleteScript(scriptId) {
    try {
      const response = await this.delete(`/api/scripts/${scriptId}`)
      return {
        success: true,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // === 健康检查 ===

  // 检查服务状态
  async healthCheck() {
    try {
      const response = await this.get('/health')
      return {
        success: true,
        status: response.status || 'unknown',
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }

  // 获取服务信息
  async getServerInfo() {
    try {
      const response = await this.get('/info')
      return {
        success: true,
        info: response,
        data: response
      }
    } catch (error) {
      return {
        success: false,
        error: error.message
      }
    }
  }
}

// 创建单例实例
const apiService = new ApiService()

export default apiService
export { ApiService }